import requests
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from aip import AipSpeech
from pygame import mixer
import time
import eyed3

retry = 0
# 百度AIP的配置
APP_ID = '你的APP ID'
API_KEY = '你的Key'
SECRET_KEY = '你的密钥'
GBAclient = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


def getBaiduAudio(FileName, context, client=GBAclient):
    global retry
    try:
        print("...............")
        res = client.synthesis(context, 'zh', 1, {
            'spd': 5,
            'vol': 10,
            'pit': 5,
            'per': 4,
        })
    except requests.exceptions.ConnectionError:
        retry += 1
        if retry <= 3:
            print("网络异常,进行第%s/3次重试" % retry)
            return getBaiduAudio(client, context)
        else:
            print("重试失败,请检查网络")
            return ""
    if not isinstance(res, dict):
        # print("合成成功")
        with open(FileName, 'wb') as f:
            f.write(res)
    elif res["err_no"] == 500:
        print("不支持的输入")
    elif res["err_no"] == 501:
        print("输入参数不正确")
    elif res["err_no"] == 502:
        print("token验证失败")
    elif res["err_no"] == 503:
        print("合成后端错误")
    else:
        print("合成失败")
        print(res)


def PlayAudio(FileName):
    Audio = eyed3.load(FileName)
    mixer.init(16000)
    mixer.music.load(FileName)
    mixer.music.play()
    time.sleep(Audio.info.time_secs)
    mixer.music.stop()


if __name__ == '__main__':
    string ='''测试一下'''
    FileName = "test.mp3"
    getBaiduAudio(FileName, string, GBAclient)
    PlayAudio(FileName)
